package com.cdu.guoxinan.www.smartcom.service.impl;

import com.cdu.guoxinan.www.smartcom.domian.vo.LogStatsVO;
import com.cdu.guoxinan.www.smartcom.domian.vo.UserLogVO;
import com.cdu.guoxinan.www.smartcom.mapper.UserLogMapper;
import com.cdu.guoxinan.www.smartcom.service.UserLogService;
import com.cdu.guoxinan.www.smartcom.unit.model.R;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserLogServiceImpl implements UserLogService {
    @Resource
    private UserLogMapper userLogMapper;

    @Override
    public LogStatsVO getLogStats() {
        return userLogMapper.queryLogStats();
    }

    @Override
    public R getLogCountByHour(Date startTime, Date endTime) {
        List<UserLogVO> userLogVOS=userLogMapper.queryRecentLogTable(startTime, endTime);

        // 用于存储时间段和对应的日志数量
        Map<String, Integer> logCountMap = new TreeMap<>();

        // 定义时间段格式化方式（例如：HH:00）
        DateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");

        // 初始化所有小时段为 0
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(endTime);
        startCal.add(Calendar.HOUR_OF_DAY, -24); // 24小时前

        Calendar tempCal = (Calendar) startCal.clone();

        for (int i = 0; i < 24; i++) {
            tempCal.add(Calendar.HOUR_OF_DAY, 1);
            String hourKey = hourFormat.format(tempCal.getTime());
            logCountMap.put(hourKey, 0);
        }

        // 遍历日志数据，按小时段累加数量
        for (UserLogVO log : userLogVOS) {
            Date timestamp = log.getTimestamp();
            String hourKey = hourFormat.format(timestamp);
            logCountMap.put(hourKey, logCountMap.getOrDefault(hourKey, 0) + 1);
        }
        return R.ok(logCountMap);
    }

    @Override
    public R getRecentLogTable(Date startTime, Date endTime, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<UserLogVO> userLogVOS=userLogMapper.queryRecentLogTable(startTime, endTime);
        PageInfo<UserLogVO> pageInfo = new PageInfo<>(userLogVOS);
        return R.ok(pageInfo.getList(), pageInfo.getTotal());
    }
}